<template>
  <!--
  查：
    1：定义api
    2:导入api
    3:进入页面就调用api
    4:存储数据并渲染
    5：接口api与分页关联(api参数与分页组件的值一样)
      a:total存储渲染到分页组件
      b:页码改变调用接口，页容量改变也要调用接口

  删
    1：定义api
    2:导入api
    3:点击删除弹出确定框
    4：点击确定框的确定调用api
    5:调用成功
       提示
       刷新列表（如果页码>1  && 当前页只有一条数据  页码--）

  持久化
     1：值修改了存储到浏览器
     2：初始值读取浏览器存储

   js-cookie
      get(key)
      set(key,value)
      remove(key)

   路由传值：
      query:
         传：this.$router.push('/xxx?参数名=参数值')
         收：this.$route.query.参数名
      params:动态路由匹配
         配制路由  {path:'/xxx/:id',component。。。}
         传：this.$router.push('/xxx/123')
         收:this.$route.params.id

   头像生成二维码
     1：创建一个弹框组件
     2：在父组件导入注册使用
     3：点击头像打开弹框
     4：在弹框内要生成二维码
        没有头像不要打开弹框，直接提示

   分配角色
     1：创建分配角色弹框组件
     2：在父组件导入注册使用
     3：点击角色打开弹框
     4：调用接口获取角色列表渲染
     5：回显当前点击项的角色
         有数据：深拷贝
         没数据：调用接口获取
     6：定义修改角色api
     7:导入修改角色api
     8:点击确定调用修改角色api
     9:调用成功
        a:提示
        b:关闭弹框
        c:清空已勾选项
        d:刷新父级（看父级列表有没有相应渲染）
 -->

  <div class="employees">
    <el-card class="top-card">
      <div class="top">
        <div class="tip">
          <i class="el-icon-info" />
          <span>当前共有{{ total }}条记录</span>
        </div>
        <div class="right">
          <el-button
            type="danger"
            size="small"
            @click="outClick"
          >普通excel导出</el-button>
          <el-button type="warning" size="small">复杂表头excel导出</el-button>
          <el-button
            type="success"
            size="small"
            @click="$router.push('/employees/import')"
          >excel导入</el-button>
          <el-button
            type="primary"
            size="small"
            @click="addEvent"
          >新增员工</el-button>
        </div>
      </div>
    </el-card>
    <el-card>
      <el-table :data="list">
        <el-table-column label="序号">
          <template v-slot="{ $index }">
            {{ (page.page - 1) * page.size + $index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="username" label="姓名" />
        <el-table-column prop="staffPhoto" label="头像">
          <template v-slot="{ row }">
            <img
              v-imgerror
              class="avatar"
              :src="row.staffPhoto"
              alt=""
              @click="imgClick(row.staffPhoto)"
            >
          </template>
        </el-table-column>
        <el-table-column prop="mobile" label="手机号" width="120px" />
        <el-table-column prop="workNumber" label="工号" />
        <!-- <el-table-column
          prop="formOfEmployment"
          label="聘用形式"
          :formatter="formatEmployment"
        /> -->
        <el-table-column prop="formOfEmployment" label="聘用形式">
          <template v-slot="{ row }">
            <div v-formatnum:hireType="row.formOfEmployment" />
          </template>
        </el-table-column>
        <!-- <template v-slot="{ row }">
            <div>
              {{ row.formOfEmployment === 1 ? '正式' : '非正式' }}
            </div>
          </template> -->
        <el-table-column prop="departmentName" label="部门" />
        <el-table-column prop="timeOfEntry" label="入职时间" />
        <!-- <el-table-column
          prop="enableState"
          :formatter="formatState"
          label="帐户状态"
        /> -->
        <el-table-column prop="enableState" label="帐户状态">
          <template v-slot="{ row }">
            <div v-formatnum:workingState="row.enableState" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300px">
          <template v-slot="{ row }">
            <el-button
              type="text"
              @click="$router.push('/employees/detail/' + row.id)"
            >查看</el-button>
            <el-button type="text">转正</el-button>
            <el-button type="text">调岗</el-button>
            <el-button type="text">离职</el-button>
            <el-button type="text" @click="roleEvent(row)">角色</el-button>
            <!-- <el-button
              v-if="
                $store.state.user.userInfo.roles.points.includes(
                  'employees_del_button'
                )
              "
              type="text"
              @click="delEvent(row.id)"
            >删除</el-button> -->
            <!-- <el-button
              v-buttonshow="'employees_del_button'"
              type="text"
              @click="delEvent(row.id)"
            >删除</el-button> -->
            <el-button
              v-if="isShowButton('employees_del_button')"
              type="text"
              @click="delEvent(row.id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="page">
        <el-pagination
          :current-page.sync="page.page"
          :page-sizes="[1, 2, 5, 10, 100, 200, 300, 400]"
          :page-size.sync="page.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="sizeChange"
          @current-change="getData"
        />
        <!-- @size-change="handleSizeChange"
          @current-change="handleCurrentChange" -->
      </div>
    </el-card>
    <!-- 新增弹框组件 -->
    <!-- ref props  v-model  .sync
        v-model
           <子组件标签  :value="父组件属性"  @input="父组件属性=$event" />
           <子组件标签  v-model="父组件属性"   />
           props:{
            value:{...}
           },
           model:{
            prop:'value',
            event:'input'
           },
           this.$emit('input',实参)

    -->
    <!-- <Add :value="show" @input="show = $event" /> -->
    <Add v-model="show" @getData="getData" />
    <!-- 二维码 -->
    <ImgCode ref="code" />
    <!-- 分配角色 -->
    <SetRole ref="role" />
  </div>
</template>
<script>
import { sysUser, sysUserDelete } from '@/api/employees'
import employeesData from '@/api/constant/employees'
import Add from './components/Add.vue'
import jsCookie from 'js-cookie'
import ImgCode from './components/ImgCode'
import SetRole from './components/setRole.vue'

// import { export_json_to_excel } from '@/vendor/Export2Excel'
export default {
  components: {
    Add,
    ImgCode,
    SetRole
  },
  data() {
    return {
      show: false,
      list: [],
      page: {
        page: 1, //	是	1	页码
        size: +jsCookie.get('employees_size') || 10 //	是	10	每页条数
      },
      total: 100
    }
  },
  created() {
    this.getData()
  },
  mounted() {
    console.log('children', this.$children)
  },
  methods: {
    async getData() {
      const res = await sysUser(this.page)
      this.list = res.data.rows
      this.total = res.data.total
      console.log('列表', res)
    },
    // 聘用形式数据转换
    formatEmployment(row, column, cellValue, index) {
      // cellValue:当前项的值
      // employeesData.hireType      [{id:1},{id:2}]    2
      // find:找出满足条件的项，找不到返回 undefined
      const findItem = employeesData.hireType.find(
        (item) => item.id === cellValue
      )
      return findItem ? findItem.value : '-'
    },
    // 帐户状态转换
    formatState(row, column, cellValue) {
      console.log(employeesData.workingState, cellValue)
      const findItem = employeesData.workingState.find(
        (item) => +item.id === +cellValue
      )
      return findItem ? findItem.value : '-'
    },
    // 新增点击事件
    addEvent() {
      this.show = true
    },
    // 删除点击事件
    async delEvent(id) {
      await this.$confirm('您确定删除该员工吗?')
      await sysUserDelete(id)
      this.$message.success('删除成功')
      if (this.page.page > 1 && this.list.length === 1) {
        this.page.page--
      }
      this.getData()
    },
    // 页容量修改
    sizeChange() {
      this.getData()
      // 页容量存储到浏览器
      jsCookie.set('employees_size', this.page.size)
    },
    // 导出excel点击
    async outClick() {
      const { export_json_to_excel } = await import('@/vendor/Export2Excel')
      // 获取所有员工数据
      const res = await sysUser({
        page: 1,
        size: 99999
      })
      // 数据转换
      const newData = res.data.rows.map((item) => {
        return [
          item.username,
          item.staffPhoto,
          item.mobile,
          item.workNumber,
          this.formatEmployment(null, null, item.formOfEmployment),
          item.departmentName,
          item.timeOfEntry,
          this.formatState(null, null, item.enableState)
        ]
      })
      console.log('所有员工数据', res)
      // 导出方法调用
      export_json_to_excel({
        header: [
          '姓名',
          '头像',
          '手机号',
          '工号',
          '聘用形式',
          '部门',
          '入职时间',
          '帐户状态'
        ],
        data: newData,
        filename: '员工列表'
      })
    },
    // 头像点击
    imgClick(img) {
      if (img) {
        this.$refs.code.showCode = true
        this.$nextTick(() => {
          // 生成二维码
          this.$refs.code.createCode(img)
        })
      } else {
        this.$message.warning('头像地址不存在！')
      }
    },
    // 角色点击
    roleEvent(row) {
      // 修改标题
      this.$refs.role.title = row.username
      // 打开弹框
      this.$refs.role.isShow = true
      // 获取角色列表
      this.$refs.role.getData()
      // 调用获取详情的方法
      this.$refs.role.getInfo(row.id)
      // console.log(row)
    }
  }
}
</script>
<style lang="scss" scoped>
.top-card {
  margin-bottom: 15px;
}
.employees {
  padding: 15px;
  .top {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .tip {
      border: 1px solid #d0edff;
      background-color: #e6f7ff;
      padding: 8px;
      i {
        color: #409eff;
        padding-right: 10px;
      }
    }
  }
}
.page {
  padding-top: 15px;
  text-align: right;
}
.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
}
</style>
